﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace MYTech.Utils
{
    public class TreeNodeHelper
    {
        public static void AfterCheck(TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
                CheckNode(e.Node);
        }

        private static bool CheckNode(TreeNode node)
        {
            bool _checked = node.Checked;
            foreach (TreeNode _node in node.Nodes)
            {
                if (_node.Checked != _checked)
                    _node.Checked = _checked;
                if (_node.Nodes.Count > 0)
                    CheckNode(_node);
            }
            ValidParentCheckState(node);
            return _checked;
        }

        private static void ValidParentCheckState(TreeNode node)
        {
            if (node.Parent != null)
            {
                if (ValidIsAllChildChecked(node.Parent) && !node.Parent.Checked)
                    node.Parent.Checked = true;
                else if (!ValidIsAllChildChecked(node.Parent) && node.Parent.Checked)
                    node.Parent.Checked = false;
                ValidParentCheckState(node.Parent);
            }
        }

        private static bool ValidIsAllChildChecked(TreeNode node)
        {
            bool _checked = true;
            foreach (TreeNode _node in node.Nodes)
            {
                _checked &= _node.Checked && ValidIsAllChildChecked(_node);
                if (!_checked)
                    return _checked;
            }
            return _checked;
        }
    }
}
